# view/register_window.py
import customtkinter as ctk
import re
import json
from utils.security import hash_password
from pathlib import Path
from utils.utils import logger


class RegisterWindow(ctk.CTkToplevel):
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent
        self.title("用户注册")
        self.geometry("400x420")
        self.resizable(False, False)
        self.grab_set()  # 模态窗口
        self.focus()

        # 数据文件路径（项目根目录下的 users.json）
        self.users_file = Path(__file__).parent.parent / "data" / "users.json"
        self.users_file.parent.mkdir(exist_ok=True)  # 自动创建 data 目录

        # 标题
        title_label = ctk.CTkLabel(self, text="新用户注册", font=("Microsoft YaHei", 18, "bold"))
        title_label.pack(pady=(20, 15))

        # 表单区域
        form_frame = ctk.CTkFrame(self, fg_color="transparent")
        form_frame.pack(pady=10)

        # 用户名
        ctk.CTkLabel(form_frame, text="用户名：", anchor="w", width=70).grid(row=0, column=0, padx=(10, 5), pady=4, sticky="w")
        self.username_entry = ctk.CTkEntry(form_frame, placeholder_text="字母/数字/下划线", width=220)
        self.username_entry.grid(row=0, column=1, padx=(0, 10), pady=4)

        # 密码
        ctk.CTkLabel(form_frame, text="密  码：", anchor="w", width=70).grid(row=1, column=0, padx=(10, 5), pady=4, sticky="w")
        self.password_entry = ctk.CTkEntry(form_frame, placeholder_text="至少6位", show="*", width=220)
        self.password_entry.grid(row=1, column=1, padx=(0, 10), pady=4)

        # 确认密码
        ctk.CTkLabel(form_frame, text="确认密码：", anchor="w", width=70).grid(row=2, column=0, padx=(10, 5), pady=4, sticky="w")
        self.confirm_password_entry = ctk.CTkEntry(form_frame, placeholder_text="再次输入密码", show="*", width=220)
        self.confirm_password_entry.grid(row=2, column=1, padx=(0, 10), pady=4)

        # 手机号
        ctk.CTkLabel(form_frame, text="手机号：", anchor="w", width=70).grid(row=3, column=0, padx=(10, 5), pady=4, sticky="w")
        self.phone_entry = ctk.CTkEntry(form_frame, placeholder_text="11位中国大陆手机号", width=220)
        self.phone_entry.grid(row=3, column=1, padx=(0, 10), pady=4)

        # 按钮区域
        btn_frame = ctk.CTkFrame(self, fg_color="transparent")
        btn_frame.pack(pady=15)

        ctk.CTkButton(btn_frame, text="注册", command=self.register, width=100, height=32).pack(side="left", padx=(0, 10))
        ctk.CTkButton(btn_frame, text="取消", command=self.destroy, width=100, height=32, fg_color="gray70").pack(side="left")

        # 绑定回车键
        self.confirm_password_entry.bind("<Return>", lambda e: self.register())

    def load_users(self):
        if self.users_file.exists():
            try:
                with open(self.users_file, "r", encoding="utf-8") as f:
                    return json.load(f)
            except Exception as e:
                logger.error(f"读取用户数据失败: {e}")
                return {}
        return {}

    def save_users(self, users):
        try:
            with open(self.users_file, "w", encoding="utf-8") as f:
                json.dump(users, f, ensure_ascii=False, indent=2)
        except Exception as e:
            logger.error(f"保存用户数据失败: {e}")
            raise

    def validate_input(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get().strip()
        confirm_password = self.confirm_password_entry.get().strip()
        phone = self.phone_entry.get().strip()

        if not username:
            self.show_error("用户名不能为空")
            return None
        if not re.match(r"^[a-zA-Z0-9_]{3,20}$", username):
            self.show_error("用户名只能包含字母、数字、下划线，长度3-20位")
            return None

        if not password:
            self.show_error("密码不能为空")
            return None
        if len(password) < 6:
            self.show_error("密码至少6位")
            return None

        if password != confirm_password:
            self.show_error("两次密码不一致")
            return None

        if not phone:
            self.show_error("手机号不能为空")
            return None
        if not re.match(r"^1[3-9]\d{9}$", phone):
            self.show_error("请输入有效的中国大陆手机号")
            return None

        return {"username": username, "password": password, "phone": phone}

    def register(self):
        user_data = self.validate_input()
        if not user_data:
            return

        users = self.load_users()

        if user_data["username"] in users:
            self.show_error("该用户名已存在，请换一个")
            return

        # 保存（明文存储仅用于演示！实际应加密）
        hashed_pw = hash_password(user_data["password"])
        users[user_data["username"]] = {
            "password_hash": hashed_pw,  # 注意字段名改为 password_hash
            "phone": user_data["phone"]
        }

        try:
            self.save_users(users)
            logger.info(f"新用户注册成功: {user_data['username']}")
            self.show_success_and_close()
        except Exception:
            self.show_error("注册失败，请重试")

    def show_error(self, message: str):
        err = ctk.CTkToplevel(self)
        err.title("错误")
        err.geometry("260x100")
        err.resizable(False, False)
        err.grab_set()
        ctk.CTkLabel(err, text=message, text_color="red", wraplength=240).pack(pady=20)
        ctk.CTkButton(err, text="确定", command=err.destroy, width=80).pack()

    def show_success_and_close(self):
        success = ctk.CTkToplevel(self)
        success.title("成功")
        success.geometry("260x100")
        success.resizable(False, False)
        success.grab_set()
        ctk.CTkLabel(success, text="注册成功！\n请使用新账号登录。", text_color="green").pack(pady=20)
        ctk.CTkButton(success, text="确定", command=lambda: [success.destroy(), self.destroy()], width=80).pack()